package com.base.cn.platform.os.service.op.giftcard;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.order.OrderSource;
import com.base.cn.platform.os.common.utils.order.PayType;
import com.base.cn.platform.os.common.utils.user.AccountBizType;
import com.base.cn.platform.os.common.utils.user.AccountHistoryType;
import com.base.cn.platform.os.common.utils.user.AccountType;
import com.base.cn.platform.os.dao.op.giftcard.OpGiftCardCodeDao;
import com.base.cn.platform.os.entity.op.giftcard.OpGiftCard;
import com.base.cn.platform.os.entity.op.giftcard.OpGiftCardCode;
import com.base.cn.platform.os.service.order.check.CreateOrderDataFrom;
import com.base.cn.platform.os.service.order.order.OrderBiz;
import com.base.cn.platform.os.service.user.account.CusUserAccountBiz;
import com.base.cn.platform.os.service.user.user.CusUserBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 礼品卡Service
 * Created by ll on 2018/05/14.
 */
@Service
public class OpGiftCardCodeBiz extends BaseBiz<OpGiftCardCode,OpGiftCardCodeDao> {

    @Autowired
    private OpGiftCardBiz opGiftCardBiz;
    @Autowired
    private CusUserBiz cusUserBiz;
    @Autowired
    private CusUserAccountBiz cusUserAccountBiz;
    @Autowired
    private OrderBiz orderBiz;


    /**
     * 搜索礼品卡列表
     * @param page
     * @param giftCardCode
     * @return
     */
    public PageInfo<OpGiftCardCode> queryOpGiftCardCodeListPage(Pagination page, OpGiftCardCode giftCardCode,
                                                                boolean giftCradeData,boolean userData,boolean courseData){
        String whereSql = whereSqlGiftCardCode(giftCardCode);
        PageInfo<OpGiftCardCode> giftCardCodes = this.findPage(whereSql,page,null);
        if (ObjectUtils.isNotEmpty(giftCardCodes)){
            giftCardCodes.setList(setGiftCardAndUserList(giftCardCodes.getList(),giftCradeData,userData,courseData));
        }
        return giftCardCodes;
    }

    /**
     * 搜索礼品卡列表
     * @param giftCardCode
     * @return
     */
    public List<OpGiftCardCode> queryOpGiftCardCodeList(OpGiftCardCode giftCardCode,boolean giftCradeData,boolean userData,boolean courseData){
        String whereSql = whereSqlGiftCardCode(giftCardCode);
        List<OpGiftCardCode> giftCardCodes = this.find(whereSql,null,null);
        giftCardCodes =setGiftCardAndUserList(giftCardCodes,giftCradeData,userData,courseData);
        return giftCardCodes;
    }


    /**
     * 批量set扩展消息
     * @param giftCardCodes
     * @param giftCardeData
     * @param userData
     * @return
     */
    public List<OpGiftCardCode> setGiftCardAndUserList(List<OpGiftCardCode> giftCardCodes,boolean giftCardeData,boolean userData,boolean courseData){
        if (ObjectUtils.isNotEmpty(giftCardCodes)){
            if (giftCardeData){
                giftCardCodes=setCardCodeCardLit(giftCardCodes,courseData);
            }
            if (userData){
                cusUserBiz.setUserData(giftCardCodes,userData);
            }
        }
        return giftCardCodes;
    }

    /**
     * 修改状态
     * @param userCardId == id
     * @param status
     * @param userId
     * @return
     */
    public void updateGiftCardStatusCode(BigDecimal userCardId, Integer status, BigDecimal userId) {
        OpGiftCardCode giftCardCode = new OpGiftCardCode();
        giftCardCode.setId(userCardId);
        giftCardCode.setStatus(status);
        giftCardCode.setUserId(userId);
        this.updateById(giftCardCode, null);
    }


    /**
     * 修改礼品卡使用状态状态
     * @param userCardId == id
     * @param UseType
     * @param userId
     * @return
     */
    public void updateGiftCardUseTypeCode(BigDecimal userCardId, Integer UseType, BigDecimal userId) {
        OpGiftCardCode giftCardCode = new OpGiftCardCode();
        giftCardCode.setId(userCardId);
        giftCardCode.setUseType(UseType);
        giftCardCode.setUserId(userId);
        this.updateById(giftCardCode, null);
    }


    /**
     * 根据卡号和类型搜索礼品卡
     * @param code
     * @param type
     * @return
     */
    public OpGiftCardCode queryGiftCardCodeByCode(String code,Integer type){
        OpGiftCardCode giftCardCode = null;
        if(StringUtils.isNotEmpty(code)){
            StringBuilder whereSql = new StringBuilder();
            whereSql.append(" code ='").append(code.trim()).append("' and status=1 ");
            if(type!=null&&type>0){
                whereSql.append(" and cardType='").append(type).append("'");
            }
            List<OpGiftCardCode> giftCardCodes = this.find(whereSql.toString(),null,null);
            if(ObjectUtils.isNotEmpty(giftCardCodes)){
                giftCardCode=giftCardCodes.get(0);
            }
        }
        return  giftCardCode;
    }


    /**
     * 条件搜索语句
     * @param giftCardCode
     * @return
     */
    public String  whereSqlGiftCardCode(OpGiftCardCode giftCardCode){
        String whereSql = " 1=1 ";
        if(giftCardCode!=null){
            if(DataUtil.idIsNotNull(giftCardCode.getGiftCardId())){
                whereSql += " and giftCardId = "+giftCardCode.getGiftCardId();
            }
            if(giftCardCode.getCardType()!=null&&giftCardCode.getCardType()>0){
                whereSql += " and cardType = "+giftCardCode.getCardType();
            }
            if (DataUtil.idIsNotNull(giftCardCode.getUserId())){
                whereSql += " and userId = "+giftCardCode.getUserId();
            }
            if(giftCardCode.getUseType()!=null&&giftCardCode.getUseType()>0){
                whereSql += " and useType = "+giftCardCode.getUseType();
            }
            if(StringUtils.isNotEmpty(giftCardCode.getCode())){
                whereSql += " and code ='"+giftCardCode.getCode()+"'";
            }
            if(giftCardCode.getStatus()!=null&&giftCardCode.getStatus()>0){
                whereSql += " and status ="+giftCardCode.getStatus();
            }else {
                whereSql += " and status !=3";
            }
            whereSql += " order by id desc ";
        }
        return whereSql;
    }


    /**
     * 通过卡号，获取促销编码
     *
     * @param cardCode 卡号
     * @return CardCode
     */
    public OpGiftCardCode queryCardCodeByNo(String cardCode) {
        if(StringUtils.isNotEmpty(cardCode)){
            List<OpGiftCardCode> cardCodeList = this.find(" code='" + cardCode.trim() + "'",null,null);
            if (ObjectUtils.isNotEmpty(cardCodeList)) {
                return cardCodeList.get(0);
            }
        }
        return null;
    }

    /**
     * 设置卡的主卡属性
     *
     * @param cardCodeList 卡编辑的列表
     */
    public List<OpGiftCardCode> setCardCodeCardLit(List<OpGiftCardCode> cardCodeList,boolean courseData) {
        if (ObjectUtils.isNotEmpty(cardCodeList)) {
            String cardIds = cardCodeList.stream().map(e -> e.getGiftCardId().toString()).collect(Collectors.joining(","));
            List<OpGiftCard> cardList = opGiftCardBiz.queryOpGiftCardListByIds(cardIds,courseData);
            if (ObjectUtils.isNotEmpty(cardList)) {
                Map<BigDecimal, OpGiftCard> cardMap = cardList.stream().collect(Collectors.toMap(OpGiftCard::getId, e -> e));
                for (OpGiftCardCode cardCode : cardCodeList) {
                    cardCode.setGiftCard(cardMap.get(cardCode.getGiftCardId()));
                }
            }
        }
        return cardCodeList;
    }

    /**
     * 特定条件的搜索礼品卡
     * @param giftCardId
     * @param status
     * @param userId
     * @param count
     * @return
     */
    public List<OpGiftCardCode> queryOpGiftCardCodesByGiftCardIdAndStatusAndIsUserData(BigDecimal giftCardId,Integer status,BigDecimal userId,Integer count){
        StringBuilder whereSql = new StringBuilder();
        whereSql.append(" status =").append(status);
        if (DataUtil.idIsNotNull(giftCardId)){
            whereSql.append(" and giftCardId =").append(giftCardId);
        }
        if (DataUtil.idIsNotNull(userId)){
            whereSql.append(" and userId=").append(userId);
        }else{
            whereSql.append(" and (userId is  null or userId =0)");
        }
        return this.find(whereSql.toString(),count,null);
    }

    /**
     * 激活礼卡
     * @param userId 用户ID
     * @return Map<String,Object>
     */
    @Transactional(rollbackFor =  IllegalArgumentException.class)
    public OpGiftCardCode activateGiftCard(OpGiftCardCode giftCardCode,BigDecimal userId) throws Exception{
        //卡类型，1学员卡，2课程卡，3充值卡
        int cardType = giftCardCode.getCardType().intValue();
        if(cardType==2 || cardType==3){
            giftCardCode.setUserId(userId);
            giftCardCode.setUseType(2);
            this.updateById(giftCardCode,null);//修改礼卡
            OpGiftCard giftCard = opGiftCardBiz.findById(giftCardCode.getGiftCardId());
            if(cardType==2){//课程卡激活
                String courseIds = giftCard.getCourseIds();
                if(StringUtils.isNotEmpty(courseIds)){
                    String shopType = "COURSE";Integer buyNum =1;
                    String[] courseId=courseIds.split(",");
                    String shopData = "";
                    for(String shopId:courseId){
                        if (StringUtils.isNotEmpty(shopId)){
                            shopData+=shopId+"-"+shopType+"-"+buyNum+",";
                        }
                    }
                    CreateOrderDataFrom createOrderDataFrom = new CreateOrderDataFrom();
                    createOrderDataFrom.setShopData(shopData);
                    createOrderDataFrom.setUserId(userId);
                    createOrderDataFrom.setAutoGive(true);//设置成系统自动赠送
                    createOrderDataFrom.setPayType(PayType.PAY_TYPE_COURSE_CART);
                    createOrderDataFrom.setOrderForm(OrderSource.ORDER_FORM_COURSE_CART);
                    orderBiz.createFreeOrder(createOrderDataFrom);
                }
            }
            if(cardType==3){//充值
                double amount = giftCard.getAmount();
                cusUserAccountBiz.updateAccountMoney(userId,amount, AccountType.VM.toString(),
                        AccountHistoryType.VMLOAD.getValue(),BigDecimal.ZERO,null,
                        null,true, AccountBizType.VM.getValue(),BigDecimal.ZERO,2,false);
            }
        }
        BigDecimal cardId = giftCardCode.getGiftCardId();
        OpGiftCard giftCard = opGiftCardBiz.findById(cardId);
        giftCard.setUseCount((giftCard.getUseCount()==null? 0 : giftCard.getUseCount()) + 1);
        opGiftCardBiz.updateById(giftCard,null);
        return giftCardCode;
    }
}
